import json
from .CharConvert import CharConvert


class TextConvert(CharConvert):
    field_type = 'text'

    @classmethod
    def to_domain(cls, field, value, **kwargs):
        if isinstance(value, str) and "%" in value:
            return [(field.name, 'ilike', value)]

        if isinstance(value, str) and "$regex" in value:
            try:
                value = json.loads(value)
            except json.JSONDecoder:
                raise ValueError("Invalid JSON string: %s" % value)
        if isinstance(value, dict):
            """
            此处参照mongo的写法进行模糊匹配，但是不去处理$options，默认都是执行忽略大小写的模糊匹配
            结构如下：
            {
                "$regex": "test"
            }

            """
            for dollar, v in value.items():
                if dollar == '$regex':
                    return [(field.name, 'ilike', v)]

        else:
            return [(field.name, '=', value)]
